-module (updatefile).

-compile(export_all).
%-export ([start/2]).



rename([],_) ->
    ok;
rename([{logfile,Mod,Num}|Rest], MaxBackupFile) ->
    if
	Num < MaxBackupFile ->
	    OFn = Mod ++ "_" ++ integer_to_list(Num) ++ ".log",
	    NFn = Mod ++ "_" ++ integer_to_list(Num+1) ++ ".log",
	    file:rename(OFn, NFn),
	    file:delete(OFn);
	true ->
	    pass
    end,
    rename(Rest,MaxBackupFile).

start(MaxBackupFile,ModName) ->
    Files = filterfile(".",ModName),
    FirstFile = lists:filter(fun({logfile,_Mod,Num}) -> Num == 1 end, Files ),
    case length(FirstFile) of
	0 ->
	    null;
	_ ->
	    rename(Files,MaxBackupFile)
    end,
    Files.

filenamesort({logfile,_,Num1},{logfile,_,Num2}) ->
    Num1 > Num2.
    
filterfile(Dir,Mod) ->
    {ok,Filenames} = file:list_dir(Dir),
    %%io:format("~p files have: ~p~n", [Dir,Filenames]),
    Logs = lists:filter(fun(Filename) -> filterlog(Filename,Mod) end, Filenames),

    NewLogs = lists:foldl( fun(Log,Acc) ->
 				   [Mod|Num] = string:tokens(filename:rootname(Log), "_"),
 				   case length(Num) of
 				       1 ->
 					   [Num1] = Num,
 					   [{logfile,Mod,list_to_integer(Num1)}|Acc];
 				       0 ->
 					   [{logfile,Mod,0}|Acc]
 				   end
 			   end, [], Logs),

    %%    NewLogs = [ {logfile,Mod,list_to_integer(Num)} || Log<-Logs, [Mod,Num] = string:tokens(filename:rootname(Log),"_")],
    lists:sort( fun filenamesort/2,NewLogs).

filterlog(I,Mod) ->
    MatchPattern = Mod ++ "_[0-9]+.log$",
    %%io:format("~p match pattern: ~ts~n", [I,MatchPattern]),
    case regexp:match(I,MatchPattern) of
	{match,_,_} ->
	    true;
	_ ->
	    false
    end.
